package com.ouyy.volunteerservice.volunteer.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ouyy.volunteerservice.volunteer.domain.po.Volunteer;
import com.ouyy.volunteerservice.volunteer.domain.po.VolunteerviewReply;
import com.ouyy.volunteerservice.volunteer.service.VolunteerService;
import com.ouyy.volunteerservice.volunteer.service.VolunteerviewReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/reply")
public class VolunteerviewReplyController {

    @Autowired
    private VolunteerviewReplyService volunteerviewReplyService;

    @Autowired
    private VolunteerService volunteerService;

    // 查询某条评论下的所有回复
    @GetMapping("/{commentId}")
    public ResponseEntity<List<VolunteerviewReply>> getRepliesByCommentId(@PathVariable("commentId") Integer commentId) {
        QueryWrapper<VolunteerviewReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", commentId).orderByAsc("reply_time"); // 按时间升序排列
        List<VolunteerviewReply> replies = volunteerviewReplyService.list(queryWrapper);
        for (VolunteerviewReply reply : replies){
            Volunteer voluneer = volunteerService.getById(reply.getUserId());
            reply.setUserName(voluneer.getName());
        }
        return ResponseEntity.ok(replies);
    }

    // 添加回复
    @PostMapping
    public ResponseEntity<VolunteerviewReply> addReply(@RequestBody VolunteerviewReply reply) {
        boolean saved = volunteerviewReplyService.save(reply);
        if (saved) {
            return ResponseEntity.ok(reply);
        } else {
            return ResponseEntity.status(500).body(null);
        }
    }

    // 修改回复
    @PutMapping("/{id}")
    public ResponseEntity<VolunteerviewReply> updateReply(@RequestBody VolunteerviewReply reply) {
        boolean updated = volunteerviewReplyService.updateById(reply);
        if (updated) {
            return ResponseEntity.ok(reply);
        } else {
            return ResponseEntity.status(404).body(null);
        }
    }

    // 删除回复
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteReply(@PathVariable("id") Integer id) {
        boolean deleted = volunteerviewReplyService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok("Reply deleted successfully.");
        } else {
            return ResponseEntity.status(404).body("Reply not found.");
        }
    }
}
